<template>
	<view class="apply-pages" v-if="isLoad">

		<view class="page-height" v-if="options.admin_id && [2,3].includes(coach_status) || is_update">
			<abnor percent="150%" @confirm="confirm" @cancel="$util.goUrl({ url: 1, openType: `navigateBack` })"
				:title="title[coach_status]" :tip="tipArr[coach_status]" :button="buttonArr[coach_status]"
				:image="image[coach_status]"></abnor>
		</view>
		<block v-else>
			<view class="apply-form">
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg b-1px-b">
						<view class="item-text">姓名</view>
						<input v-model="form.coach_name" type="text" class="item-input flex-1" maxlength="20"
							:placeholder="rule[0].errorMsg" />
					</view>
					<view class="flex-between pl-lg pr-lg b-1px-b">
						<view class="item-text">性别</view>
						<view class="item-input flex-1 flex-y-center">
							<view @tap.stop="form.sex = index" class="flex-y-center" :class="[{'mr-lg':index==0}]"
								:style="{color:form.sex == index ? primaryColor:''}" v-for="(item,index) in ['男','女']"
								:key="index"><i class="iconfont icon-xuanze mr-sm"
									:class="[{'icon-xuanze-fill':form.sex == index}]"></i>{{item}}
							</view>
						</view>
					</view>
					<view class="flex-between pl-lg pr-lg b-1px-b">
						<view class="item-text">手机号</view>
						<input v-model="form.mobile" type="text" class="item-input flex-1"
							:placeholder="rule[1].errorMsg" />
					</view>
					<view class="flex-between pl-lg pr-lg b-1px-b">
						<view class="item-text">从业年份</view>
						<input v-model="form.work_time" type="number" class="item-input flex-1"
							:placeholder="rule[2].errorMsg" />
					</view>
					<view class="flex-between pl-lg pr-lg b-1px-b">
						<view class="item-text">意向工作城市</view>
						<view class="item-input text">
							<picker @change="pickerChange($event)" :value="cityIndex" :range="cityList"
								range-key="title">
								<view class="flex-y-center">
									{{cityIndex!=-1?cityList[cityIndex].title:'请选择'}}
									<i class="iconfont icon-right ml-sm" style="font-size: 28rpx;"></i>
								</view>
							</picker>
						</view>
					</view>
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">所在地址</view>
						<view class="item-input text flex-1">
							<view @tap.stop="toChooseLocation" class="flex-y-center text-right">
								<view class="flex-1 text-right">{{form.address || `点击右边图标设置`}}</view><i
									class="iconfont iconjuli ml-sm" :style="{color: primaryColor}"></i>
							</view>
						</view>
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">技师简介</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<textarea v-model="form.text" class="item-textarea pd-lg" maxlength="300" placeholder="输入技师简介" />
					<view class="text-right pb-lg pr-lg">
						{{form.text.length>300?300:form.text.length}}/300
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">身份证号</view>
						<input v-model="form.id_code" type="text" class="item-input flex-1"
							:placeholder="rule[6].errorMsg" />
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">身份证照片</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" :imagelist="form.id_card" imgtype="id_card" imgclass="md"
							text="身份证人像面" :imgsize="1"></upload>
						<upload @upload="imgUpload" :imagelist="form.id_card_fan" imgtype="id_card_fan" imgclass="md"
							text="身份证国徽面" :imgsize="1"></upload>
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" :imagelist="form.id_card_people" imgtype="id_card_people"
							imgclass="md" text="手持身份证照片" :imgsize="1"></upload>
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">资格证书</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.license" imgtype="license"
							text="上传图片" :imgsize="15">
						</upload>
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">工作形象照</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" :imagelist="form.work_img" imgtype="work_img" text="上传图片"
							:imgsize="1">
						</upload>
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">个人生活照</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.self_img" filetype="picture"
							imgtype="self_img" text="上传图片" :imgsize="9">
						</upload>
					</view>
				</view>
				<view class="fill-base mt-md radius-16">
					<view class="flex-between pl-lg pr-lg">
						<view class="item-text">个人视频介绍</view>
						<input :disabled="true" type="text" class="item-input flex-1" />
					</view>
					<view class="flex-between pl-lg pr-lg pb-md">
						<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.video" filetype="video"
							imgtype="video" text="上传视频" :imgsize="1">
						</upload>
					</view>
				</view>
				<view class="flex-center f-caption c-caption pd-lg">
					{{options.is_edit == 1 ? '编辑资料将进入重新审核，审核通过之前将显示原资料' : '平台不会通过任何渠道泄露您的个人信息，请放心输入'}}
				</view>
			</view>

			<view class="space-max-footer"></view>

			<auth :needAuth="userInfo && !userInfo.nickName" :must="true" type="userInfo" @go="submit">
				<fix-bottom-button :text="[{text:'确定申请',type:'confirm'}]" bgColor="#fff"></fix-bottom-button>
			</auth>
		</block>
	</view>
</template>

<script>
	import wPicker from "@/components/w-picker/w-picker.vue";
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {
			wPicker
		},
		data() {
			return {
				isLoad: false,
				options: {},
				cityList: [],
				cityIndex: -1,
				// -1未申请，1审核中，2审核通过，3取消授权，4审核失败(可再次申请)
				tipArr: {
					'-1': [{
						text: '审核中不可编辑资料',
						color: 0
					}],
					'2': [{
						text: '快去管理订单吧',
						color: 0
					}],
					'3': [{
						text: '请联系平台管理人员询问原因',
						color: 0
					}]
				},
				buttonArr: {
					'-1': [{
						text: '返回',
						type: 'cancel'
					}],
					'2': [{
						text: '去管理',
						type: 'confirm'
					}],
					'3': [{
						text: '再次申请',
						type: 'confirm'
					}, {
						text: '个人中心',
						type: 'cancel'
					}]
				},
				title: {
					'-1': '您已经成功提交申请',
					'2': '您已经是技师了',
					'3': '平台管理员已取消授权'
				},
				image: {
					'-1': 'https://lbqny.migugu.com/admin/public/apply_wait.jpg',
					'2': 'https://lbqny.migugu.com/admin/public/apply_suc.jpg',
					'3': 'https://lbqny.migugu.com/admin/public/apply_fail.jpg'
				},
				is_update: 0,
				coach_status: 0,
				form: {
					id: 0,
					coach_name: '', //姓名 
					mobile: '', //手机号 
					sex: 0, //性别 
					work_time: '', //从业年份 
					// city: '', //城市 
					lng: '',
					lat: '',
					address: '', //详细地址 
					text: '', //备注 
					id_code: '', //身份证号
					id_card: [], //身份证
					id_card_fan: [], // 身份证反面
					id_card_people: [], //手持身份证
					license: [], //资格证书
					work_img: [], // 工作照
					self_img: [], // 生活照
					city_id: '', // 城市 id
					video: []
				},
				rule: [{
						name: "coach_name",
						checkType: "isNotNull",
						errorMsg: "输入您的姓名",
						regType: 2
					},
					{
						name: "mobile",
						checkType: "isMobile",
						errorMsg: "输入手机号"
					}, {
						name: "work_time",
						checkType: "isNotNull",
						errorMsg: "请输入从业年份，例如：5"
					}, {
						name: "city_id",
						checkType: "isNotNull",
						errorMsg: "请选择意向工作城市"
					},
					{
						name: "address",
						checkType: "isNotNull",
						errorMsg: "请选择所在地址"
					}, {
						name: "text",
						checkType: "isNotNull",
						errorMsg: "请输入技师简介",
						regType: 2
					}, {
						name: "id_code",
						checkType: "isIdCard",
						errorMsg: "输入您的身份证号码"
					},
					{
						name: "id_card",
						checkType: "isNotNull",
						errorMsg: "请上传身份证人像面"
					},
					{
						name: "id_card_fan",
						checkType: "isNotNull",
						errorMsg: "请上传身份证国徽面"
					},
					{
						name: "id_card_people",
						checkType: "isNotNull",
						errorMsg: "请上传手持身份证照片"
					},
					{
						name: "license",
						checkType: "isNotNull",
						errorMsg: "请上传资格证书"
					},
					{
						name: "work_img",
						checkType: "isNotNull",
						errorMsg: "请上传工作形象照"
					},
					{
						name: "self_img",
						checkType: "isNotNull",
						errorMsg: "请上传个人生活照"
					},
				],
				lockTap: false
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			userInfo: state => state.user.userInfo,
			location: state => state.user.location,
		}),
		async onLoad(options) {
			let {
				is_edit = 0
			} = options
			options.is_edit = is_edit
			options = await this.updateCommonOptions(options)
			this.options = options
			this.$util.showLoading()
			await this.initIndex()
			let {
				admin_id = 0,
			} = options
			let {
				coach_status
			} = this
			uni.setNavigationBarTitle({
				title: is_edit ? '编辑资料' : admin_id && [2, 3].includes(coach_status) ? `` : `申请技师`
			})
			this.isLoad = true
		},
		methods: {
			...mapActions(['getUserInfo', 'updateCommonOptions']),
			...mapMutations(['updateUserItem']),
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.$jweixin.wxReady(() => {
						this.$jweixin.hideOptionMenu()
					})
				}
				// #endif
				await this.getCityList()
				let data = await this.$api.technician.coachInfo()
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				if (data && !data.id) {
					this.$util.hideAll()
					return
				}
				data.id_card = data.id_card.map(item => {
					return {
						path: item
					}
				})
				data.id_card_fan = [data.id_card[1]]
				data.id_card_people = [data.id_card[2]]
				data.id_card.splice(1, 3)
				data.license = data.license.map(item => {
					return {
						path: item
					}
				})
				data.work_img = [{
					path: data.work_img
				}]
				data.self_img = data.self_img.map(item => {
					return {
						path: item
					}
				})
				data.video = data.video && data.video.length > 0 ? [{
					path: data.video
				}] : []
				this.cityIndex = this.cityList.findIndex(item => {
					return item.id == data.city_id
				})
				for (let key in this.form) {
					this.form[key] = data[key]
				}
				this.coach_status = data.is_update == 1 ? -1 : data.status
				this.is_update = data.is_update
				this.$util.hideAll()
			},
			initRefresh() {
				this.initIndex(true)
			},
			async getCityList() {
				let {
					location
				} = this
				if (!location.lat) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						// await this.$jweixin.initJssdk();
						await this.$jweixin.wxReady2();
						let {
							latitude: lat = 0,
							longitude: lng = 0
						} = await this.$jweixin.getWxLocation()
						location = {
							lng,
							lat,
							address: '定位失败',
							province: '',
							city: '',
							district: ''
						}
						if (lat && lng) {
							let key = `${lat},${lng}`
							let data = await this.$api.base.getMapInfo({
								location: key
							})
							let {
								status,
								result
							} = JSON.parse(data)
							if (status == 0) {
								let {
									address,
									address_component
								} = result
								let {
									province,
									city,
									district
								} = address_component
								location = {
									lng,
									lat,
									address,
									province,
									city,
									district
								}
							}
						}
					}
					// #endif
					// #ifndef H5
					location = await this.$util.getBmapLocation()
					// #endif

					this.updateUserItem({
						key: 'location',
						val: location
					})
				}

				let {
					lng = 0,
						lat = 0
				} = location
				if (lat && lng) {
					let city = await this.$api.base.getCity({
						lng,
						lat
					})
					this.$util.hideAll()
					this.cityList = city
					this.form.city_id = city.length > 0 ? city[0].id : 0
				}
			},
			pickerChange(e, val) {
				console.log('picker发送选择改变，携带值为', e.target.value)
				this.cityIndex = e.target.value
				this.form.city_id = this.cityList[this.cityIndex].id
			},
			imgUpload(e) {
				let {
					imagelist,
					imgtype
				} = e;
				this.form[imgtype] = imagelist;
			},
			// 选择地区
			async toChooseLocation(e) {
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				let [, {
					address = '',
					longitude,
					latitude
				}] = await uni.chooseLocation();
				if (!address) return
				this.form.address = address
				this.form.lng = longitude
				this.form.lat = latitude
			},
			// 去管理/再次申请
			async confirm() {
				let {
					coach_status
				} = this
				let page = {
					2: `/pages/mine`,
					3: `/technician/pages/apply`,
				}
				let url = page[coach_status]
				this.$util.log(url)
				this.$util.goUrl({
					url,
					openType: `reLaunch`
				})
			},
			//表单验证
			validate(param) {
				let validate = new this.$util.Validate();
				this.rule.map(item => {
					let {
						name,
					} = item
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			async submit() {
				let param = this.$util.deepCopy(this.form)
				let arr = ['id_card', 'id_card_fan', 'id_card_people', 'work_img', 'video']
				arr.map(item => {
					param[item] = param[item].length > 0 ? param[item][0].path : ''
				})
				param.license = param.license.map(item => {
					return item.path
				})
				param.self_img = param.self_img.map(item => {
					return item.path
				})
				let msg = this.validate(param);
				if (msg) {
					this.$util.showToast({
						title: msg
					});
					return;
				}
				let {
					admin_id = 0
				} = this.options
				if (admin_id) {
					param.admin_id = admin_id
				}
				param.id_card = [param.id_card, param.id_card_fan, param.id_card_people]
				delete param.id_card_fan
				delete param.id_card_people
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let {
						is_edit = 0
					} = this.options
					let methodModel = param.id && is_edit ? 'coachUpdateV2' : 'coachApply'
					await this.$api.technician[methodModel](
						param)
					this.$util.hideAll()
					let msg = param.id && is_edit ? `` : `,即将跳转个人中心`
					this.$util.showToast({
						title: `提交成功${msg}`,
					})
					setTimeout(() => {
						if (param.id && is_edit) {
							this.coach_status = -1
							this.is_update = 1
							return
						}
						this.$util.back()
						this.$util.goUrl({
							url: '/pages/mine',
							openType: `reLaunch`
						})
					}, 1500)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}

			}
		}
	}
</script>


<style lang="scss">
	.page-height {
		width: 100%;
		height: 100vh;
		background: #fff;
	}
</style>
